<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
    ];

    /**
     * 获取个人URL
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int $money 余额
     * @param int $user_id 会员ID
     * @param string $memo 备注
     */
    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员积分
     * @param int $score 积分
     * @param int $user_id 会员ID
     * @param string $memo 备注
     */
    public static function score($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $before = $user->score;
                $after = $user->score + $score;
                $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['score' => $after, 'level' => $level]);
                //写入日志
                ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }

    /**
     * 小程序用户登录
     * @param string $params
     * @return int
     * @throws
     */
    public function login(string $params): int
    {
        $params = json_decode($params, true);
        // 判断当前openid用户是否已存在
        if ($rows = $this->where(['openid' => $params['openId']])->lock(true)->find()) {
            return $rows->id;
        }
        Db::startTrans();
        try {
            $this->allowField(true)->save([
                'openid' => $params['openId'],
                'nickname' => $params['nickName'],
                'gender' => $params['gender'],
                'avatar' => $params['avatarUrl'],
                'status' => 'normal'
            ]);
            Db::commit();
            return $this->id;
        } catch (Exception $exception) {
            Db::rollback();
            throw new Exception($exception->getMessage());
        }
    }

    /**
     * 用户手机号绑定
     * @param array $params
     * @return int
     * @throws Exception
     * */
    public function bindMobile(array $params): int
    {
        if (!$rows = $this->where(['openid' => $params['openid']])->lock(true)->find()) {
            throw new Exception('请先授权登录');
        }

        // 检测绑定的手机号是否已被他人占用
        $mobile = $this->where(['mobile' => $params['phoneNumber']])->lock(true)->find();
        if ($mobile && !empty($mobile['openid']) && $mobile['openid'] != $params['openid']) {
            throw new Exception('此手机号已被绑定');
        }

        // 如果openid存在，并且也绑定是此手机号则反直接返回登陆
        if ($rows && $rows['mobile'] == $params['phoneNumber']) {
            return $rows->id;
        }

        Db::startTrans();
        try {
            $rows->allowField(true)->save([
                'mobile' => $params['phoneNumber'],
                'username' => $params['phoneNumber'],
                'status' => 'normal',
            ]);
            Db::commit();
            return $rows->id;
        } catch (Exception $exception) {
            Db::rollback();
            throw new Exception($exception->getMessage());
        }
    }

    /**
     * 更新组别
     * @param array $params
     * @param int $uid
     * @return bool
     * @throws
     */
    public function saveCityGroup(array $params, int $uid): bool
    {
        $save['city_group_id'] = $params['city_group_id'];
        $save['createtime'] = time();
        $ids = [];
        if ($rows = $this->get(['id' => $uid])) {
            $ids['id'] = $uid;
        }
        Db::startTrans();
        try {
            $result = $this->allowField(true)->save($save, array_filter($ids));
            if ($result) {
                Db::commit();
                return true;
            }
            throw new Exception('加入组成功');
        } catch (Exception $exception) {
            Db::rollback();
            throw new Exception($exception->getMessage());
        }
    }

    /**
     * 修改头像
     * @param array $params
     * @param int $uid
     * @return bool
     * @throws
     */
    public function editAvatar(array $params, int $uid): bool
    {
        if (!$rows = $this->get(['id' => $uid])) {
            throw new Exception('用户不存在');
        }
        Db::startTrans();
        try {
            $result = $rows->allowField(true)->save(['avatar' => $params['avatar']]);
            if ($result) {
                Db::commit();
                return true;
            }
            throw new Exception('修改头像失败');
        } catch (Exception $exception) {
            Db::rollback();
            throw new Exception($exception->getMessage());
        }
    }

    /**
     * 修改昵称
     * @param array $params
     * @param int $uid
     * @return bool
     * @throws
     */
    public function editNickname(array $params, int $uid): bool
    {
        if (!$rows = $this->get(['id' => $uid])) {
            throw new Exception('用户不存在');
        }
        Db::startTrans();
        try {
            $result = $rows->allowField(true)->save(['nickname' => $params['nickname']]);
            if ($result) {
                Db::commit();
                return true;
            }
            throw new Exception('修改昵称失败');
        } catch (Exception $exception) {
            Db::rollback();
            throw new Exception($exception->getMessage());
        }
    }

}
